package com.iris.netty.review;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Set;

public class NioServer2 {
    public static void main(String[] args) throws IOException {
        ServerSocketChannel socketChannel = ServerSocketChannel.open();
        socketChannel.bind(new InetSocketAddress(8889));
        socketChannel.configureBlocking(false);
        Selector selector = Selector.open();
        socketChannel.register(selector, SelectionKey.OP_ACCEPT);


        while(true){
            selector.select();
            Set<SelectionKey> set = selector.selectedKeys();
            String str = "";
            for (SelectionKey key : set) {

                if(key.isAcceptable()){
                    ServerSocketChannel channel = (ServerSocketChannel) key.channel();
                    SocketChannel socket = channel.accept();
                    socket.configureBlocking(false);
                    socket.register(selector,SelectionKey.OP_READ);
                }else if (key.isReadable()){
                    SocketChannel readChannel = (SocketChannel) key.channel();
                    readChannel.configureBlocking(false);
                    ByteBuffer byteBuffer = ByteBuffer.allocate(128);
                    int count = readChannel.read(byteBuffer);
                    if(count!=-1){
                        str = new String(byteBuffer.array());
                        System.out.println(str);
                        ByteBuffer outBuffer = ByteBuffer.wrap("ok".getBytes());
                        readChannel.write(outBuffer);
                        if("end".equals(str)){
                            key.cancel();
                            readChannel.close();
                        }
                    }else{
                        System.out.println("客户端关闭");
                        key.cancel();
                    }
                }
            }
            set.clear();
        }
    }
}
